package com.example.demo.listen;

import com.example.demo.common.ConnectionContainer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yuaneg 2018/12/12
 */
@Slf4j
@Component
public class TxTransactionTimer {

    @Autowired
    private TxTransactionListen txTransactionListen;

    @Value("${tc.transaction.timeOut:600000}")
    private Long timeOut;

    @Scheduled(fixedDelayString = "${tc.transaction.delay:100}")
    public void setTimer() {
        Map<String, ConnectionContainer> failConnection = new HashMap<>();
        Map<String, ConnectionContainer> connectionModelMap = txTransactionListen.getConnectionMap();
        txTransactionListen.getConnectionMap().forEach((K, V) -> {
            if (System.currentTimeMillis() - V.getTime() > timeOut) {
                log.error("事物通知超时");
                connectionModelMap.remove(K);
                failConnection.put(K, V);
            }
        });
        txTransactionListen.setConnectionMap(connectionModelMap);
        failConnection.forEach((T, V) -> {
            Connection connection = V.getConnection();
            try {
                if (!connection.isClosed()) {
                    connection.rollback();
                    connection.close();
                }
            } catch (SQLException e) {
                log.error("超时事物以被关闭", e);
            }
        });
    }
}

